package com.project.dao;
import com.project.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
@Repository
//@Component
public class UserDao {
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate=jdbcTemplate;
    }
    public int getMatchCount(String userName,String password){
        String sqlStr = " select count(*) from tusers where username = ? and password = ? ";
        //return jdbcTemplate.queryForInt(sqlStr,new Object[]{userName,password});
        //queryForInt方法过时 改用queryForObject 在方法的第三个参数写明返回类型 如String 则写成String.class
        return jdbcTemplate.queryForObject(sqlStr,new Object[]{userName,password},Integer.class);
//        return jdbcTemplate.queryForObject(sqlStr,new Object[]{userName,password},Integer.class);
    }

    public User findUserByUserName(String username){
        String sqlStr = " select * from tusers where username = ? ";
        User user = new User();
        jdbcTemplate.query(sqlStr, new Object[]{username},
                new RowCallbackHandler() {
                    @Override
                    public void processRow(ResultSet resultSet) throws SQLException {
                        user.setUsername(resultSet.getString("username"));
//                        System.out.println(user.getUsername());
                    }
                });
        return user;
    }

//    public void updateLoginInfo(User user){
//        String sqlStr = " update t_user set credits = ? , last_visit = ? , last_ip = ? where user_id = ? ";
//        jdbcTemplate.update(sqlStr,new Object[]{user.getCredits(),user.getLastVisit(),user.getLastIp(),user.getUserId()});
//    }

}
